// app/components/auth/countdown.tsx - 验证码倒计时组件
'use client'

import { useState, useEffect } from 'react'

/**
 * @interface CountdownProps
 * @description 倒计时组件属性接口
 * @property {number} [initialSeconds] - 初始倒计时秒数，默认60秒
 * @property {function} [onCountdownEnd] - 倒计时结束时的回调函数
 */
interface CountdownProps {
  initialSeconds?: number;
  onCountdownEnd?: () => void;
}

/**
 * @component Countdown
 * @description 倒计时按钮组件，显示剩余时间并处理倒计时逻辑
 * @param {CountdownProps} props - 组件属性
 * @returns {JSX.Element} 倒计时按钮
 */
export default function Countdown({ initialSeconds = 60, onCountdownEnd }: CountdownProps) {
  const [seconds, setSeconds] = useState(initialSeconds)

  useEffect(() => {
    if (seconds <= 0) {
      onCountdownEnd?.()
      return
    }

    const timer = setInterval(() => {
      setSeconds((prev) => {
        if (prev <= 1) {
          clearInterval(timer)
          onCountdownEnd?.()
          return 0
        }
        return prev - 1
      })
    }, 1000)

    return () => clearInterval(timer)
  }, [seconds, onCountdownEnd])

  return (
    <button
      type="button"
      disabled={seconds > 0}
      className="px-4 py-2 text-sm text-blue-600 bg-blue-50 rounded-md disabled:opacity-50 disabled:cursor-not-allowed"
    >
      {seconds > 0 ? `${seconds}秒后重试` : '重新发送'}
    </button>
  )
}
